package com.hxd.otc.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.CardView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.api.Constant;
import com.hxd.otc.common.ApiConstants;
import com.hxd.otc.dialog.SingBlocksDialog;
import com.hxd.otc.module.fiat_deal.bean.DealTeamBean;
import com.hxd.otc.widget.BlocksToast;

import java.lang.ref.SoftReference;
import java.util.List;


/**
 * 作  者 :  胡庆岭
 * 时  间 :  2018/4/25 12:26
 * 描  述 :  ${TODO}
 */
public class UIUtils {
    @SuppressLint("StaticFieldLeak")
    private static Context mContext;

    public static void init(@NonNull Context context) {
        mContext = context;
    }

    public static Context getContext() {
        synchronized (UIUtils.class) {
            if (mContext == null) {
                throw new NullPointerException("Context not is null");
            }
        }
        return mContext;
    }

    public static String getString(@StringRes int resData, Object o) {
        return UIUtils.getContext().getString(resData, o);
    }

    /**
     * 截屏
     *
     * @param viewGroup
     * @return
     */
    public static Bitmap cropWindowBitmap(@NonNull ViewGroup viewGroup) {
        int height = 0;
        for (int i = 0; i < viewGroup.getChildCount(); i++) {
            height += viewGroup.getChildAt(i).getHeight();
        }
        Bitmap bitmap = Bitmap.createBitmap(viewGroup.getWidth(), height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        viewGroup.draw(canvas);
        return bitmap;
    }

    /**
     * 强制弹出软键盘
     *
     * @param context 上下文
     * @param view    view
     */
    public static void showKeyboard(@NonNull Context context, @NonNull final View view) {
        final InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            view.setFocusable(true);
            view.setFocusableInTouchMode(true);
            view.requestFocus();
            final Handler handler = new Handler();
            handler.postDelayed(new InputMethodRunnable(handler, inputMethodManager, view), 100);
        }
    }

    public static void dismissDialog(Dialog dialog) {
        if (dialog == null) return;
        dialog.setOnDismissListener(null);
        if (dialog.isShowing()) dialog.dismiss();
    }

    public static void dismissDialogFragment(DialogFragment dialogFragment) {
        if (dialogFragment == null) return;
        dialogFragment.dismissAllowingStateLoss();
    }


    public static class InputMethodRunnable implements Runnable {
        private InputMethodManager mInputMethodManager;
        private Handler mHandler;
        private View mView;

        InputMethodRunnable(@NonNull Handler handler, @NonNull InputMethodManager inputMethodManager, @NonNull View view) {
            this.mInputMethodManager = inputMethodManager;
            this.mHandler = handler;
            this.mView = view;
        }

        @Override
        public void run() {
            if (mInputMethodManager.isActive()) {
                mInputMethodManager.showSoftInput(mView, 0);
            }
            mHandler.removeCallbacks(this);
            mHandler = null;
            mView = null;
            this.mInputMethodManager = null;

        }
    }

    public static void clearImageStatus(@NonNull final EditText editText, @NonNull final View clearView) {
        clearView.setVisibility(!TextUtils.isEmpty(editText.getText()) && TextUtils.getTrimmedLength(editText.getText()) > 0 ? View.VISIBLE : View.GONE);
    }

    public static void clearImageStatus(@NonNull final EditText editText, @NonNull final View clearView, boolean isListener) {
        UIUtils.clearImageStatus(editText, clearView);
        if (isListener) {
            clearView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clearView.setVisibility(View.GONE);
                    editText.setText(null);
                }
            });
        }
    }

    public static void editInputListener(@NonNull final EditText editText, @NonNull final View view) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                UIUtils.clearImageStatus(editText, view);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    /**
     * 密码可见状态监听
     *
     * @param checkBox
     * @param editText
     */
    public static void passwordChangeStatusListener(@NonNull CheckBox checkBox, @NonNull final EditText editText) {
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                editText.setInputType(!isChecked ? InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD : InputType.TYPE_CLASS_TEXT);
                editText.setSelection(editText.getText().length());
            }
        });
    }

    /**
     * 打开相册
     *
     * @param activity
     * @param requestCode
     */
    public static void openAlbum(@NonNull Activity activity, int requestCode) {
        Intent intent = new Intent();
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            intent.setAction(Intent.ACTION_GET_CONTENT);
        } else {
            intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
        }
        activity.startActivityForResult(intent, requestCode);
    }

    public static void addTeamView(@NonNull CardView cardView, int checkTeamPosition, @NonNull List<DealTeamBean> data,
                                   final OnDealTeamItemClickListener listener) {
        if (data.size() > 0) {
            for (int i = 0; i < data.size(); i++) {

                final LinearLayout linearLayout = new LinearLayout(cardView.getContext());
                linearLayout.setOrientation(LinearLayout.VERTICAL);
                linearLayout.setClickable(true);
                if (i == checkTeamPosition) {
                    linearLayout.setBackgroundColor(ContextCompat.getColor(cardView.getContext(), R.color.color_FFF6F6F6));
                } else {
                    linearLayout.setBackgroundResource(R.drawable.selector_item_click);
                }

                cardView.addView(linearLayout);
                CardView.LayoutParams LinearParams = (CardView.LayoutParams) linearLayout.getLayoutParams();
                LinearParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
                LinearParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
                LinearParams.setMargins(0, (data.get(i).height + DataUtils.dp2px(cardView.getContext(), 0.5f)) * i, 0, 0);
                linearLayout.setLayoutParams(LinearParams);

                TextView textView = new TextView(cardView.getContext());
                textView.setText(data.get(i).transactionPair);
                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                textView.setTextColor(ContextCompat.getColor(cardView.getContext(), R.color.color_FF323232));
                textView.setGravity(Gravity.CENTER);
                linearLayout.addView(textView);
                LinearLayout.LayoutParams textViewParams = (LinearLayout.LayoutParams) textView.getLayoutParams();
                textViewParams.width = data.get(i).width;
                textViewParams.height = data.get(i).height;
                textView.setLayoutParams(textViewParams);
                if (i != data.size() - 1) {
                    View line = new View(cardView.getContext());
                    line.setBackgroundColor(ContextCompat.getColor(cardView.getContext(), R.color.color_Line));
                    linearLayout.addView(line);
                    LinearLayout.LayoutParams lineParams = (LinearLayout.LayoutParams) line.getLayoutParams();
                    lineParams.width = data.get(i).width;
                    lineParams.height = DataUtils.dp2px(cardView.getContext(), 0.5f);
                    lineParams.gravity = Gravity.CENTER;
                    line.setLayoutParams(lineParams);
                }

                final int finalI = i;
                linearLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (listener != null) {
                            listener.onClickItem(linearLayout, finalI);
                        }
                    }
                });

            }
        }

    }

    public static void addTeamView(@NonNull CardView cardView, int checkTeamPosition, @NonNull String[] data, final OnDealTeamItemClickListener listener) {
        if (data.length > 0) {
            for (int i = 0; i < data.length; i++) {

                final LinearLayout linearLayout = new LinearLayout(cardView.getContext());
                linearLayout.setOrientation(LinearLayout.VERTICAL);
                linearLayout.setClickable(true);
                if (i == checkTeamPosition) {
                    linearLayout.setBackgroundColor(ContextCompat.getColor(cardView.getContext(), R.color.color_FFF6F6F6));
                } else {
                    linearLayout.setBackgroundResource(R.drawable.selector_item_click);
                }

                cardView.addView(linearLayout);
                CardView.LayoutParams LinearParams = (CardView.LayoutParams) linearLayout.getLayoutParams();
                LinearParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
                LinearParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
                LinearParams.setMargins(0, (DataUtils.dp2px(UIUtils.getContext(), 35) + DataUtils.dp2px(cardView.getContext(), 0.5f)) * i, 0, 0);
                linearLayout.setLayoutParams(LinearParams);

                TextView textView = new TextView(cardView.getContext());
                textView.setText(data[i]);
                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                textView.setTextColor(ContextCompat.getColor(cardView.getContext(), R.color.color_FF323232));
                textView.setGravity(Gravity.CENTER);
                linearLayout.addView(textView);
                LinearLayout.LayoutParams textViewParams = (LinearLayout.LayoutParams) textView.getLayoutParams();
                textViewParams.width = DataUtils.dp2px(UIUtils.getContext(), 105);
                textViewParams.height = DataUtils.dp2px(UIUtils.getContext(), 35);
                textView.setLayoutParams(textViewParams);
                if (i != data.length - 1) {
                    View line = new View(cardView.getContext());
                    line.setBackgroundColor(ContextCompat.getColor(cardView.getContext(), R.color.color_Line));
                    linearLayout.addView(line);
                    LinearLayout.LayoutParams lineParams = (LinearLayout.LayoutParams) line.getLayoutParams();
                    lineParams.width = DataUtils.dp2px(UIUtils.getContext(), 105);
                    lineParams.height = DataUtils.dp2px(cardView.getContext(), 0.5f);
                    lineParams.gravity = Gravity.CENTER;
                    line.setLayoutParams(lineParams);
                }

                final int finalI = i;
                linearLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (listener != null) {
                            listener.onClickItem(linearLayout, finalI);
                        }
                    }
                });

            }
        }

    }

    public static void inputNumber(@NonNull final EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (editText.getText().toString().trim().startsWith(".")) {
                    editText.setText(new StringBuffer().append(0).append("."));
                    editText.setSelection(editText.getText().length());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    /**
     * 调用发送短信
     *
     * @param activity
     * @param messageData
     */
    public static void sendMessage(@NonNull Activity activity, @NonNull String messageData) {
        Intent smsIntent = new Intent(Intent.ACTION_VIEW);
        smsIntent.setData(Uri.parse("smsto:"));
        smsIntent.setType("vnd.android-dir/mms-sms");//必须指定type
        /*smsIntent.putExtra("address", phone);//address字段不能改*/
        smsIntent.putExtra("sms_body", messageData);//sms_body 不能改
        activity.startActivity(smsIntent);
    }

    public interface OnDealTeamItemClickListener {
        void onClickItem(View v, int position);
    }

    public static void setPayPasswordEditText(EditText etPayPassword) {
        if (etPayPassword == null) return;
        etPayPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        etPayPassword.setFilters(new InputFilter[]{
                new InputFilter.LengthFilter(Constant.PAY_PASSWORD_MAX_LENGTH),
                DigitsKeyListener.getInstance(ResourceUtil.getString(R.string.pay_password_digits))});
    }

    public static void setLoginPasswordEditText(EditText etLoginPassword) {
        if (etLoginPassword == null) return;
        etLoginPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        etLoginPassword.setFilters(new InputFilter[]{
                new InputFilter.LengthFilter(Constant.LOGIN_PASSWORD_MAX_LENGTH),
                DigitsKeyListener.getInstance(ResourceUtil.getString(R.string.login_password_digits))});
    }

    public static void setGoogleCodeEditText(EditText googleEditText) {
        if (googleEditText == null) return;
        googleEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
    }

    public static void setPhoneVerCodeEditText(EditText phoneVerCodeEditText) {
    }

    public static void setEmailVerCodeEditText(EditText emailVerCodeEditText) {
    }

    public static String getServiceImageUrlByPath(String path) {
        return ApiConstants.SERVICE_IMAGE_BASE_URL + path;
    }

    /**
     * 弹出软键盘
     *
     * @param view view
     */
    public static void showSoftKeyboard(View view) {
        if (view == null)
            return;

        //当view没有获得焦点就令其获取焦点
        if (!view.isFocusable())
            view.setFocusable(true);
        if (!view.isFocusableInTouchMode())
            view.setFocusableInTouchMode(true);
        if (!view.isFocused()) {
            view.requestFocus();
        }
        //显示软键盘
        InputMethodManager inputMethodManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            inputMethodManager.showSoftInput(view, 0);
            inputMethodManager.showSoftInputFromInputMethod(view.getWindowToken(), 0);
        }
    }

    /**
     * 掩藏软键盘
     *
     * @param view
     */
    public static void hideSoftKeyboard(View view) {
        if (view == null)
            return;
        View focusView = null;
        if (view instanceof EditText)//判断view是否是EditText
            focusView = view;
        Context context = view.getContext();
        if (context != null && context instanceof Activity) {//context得是Activity
            Activity activity = ((Activity) context);
            focusView = activity.getCurrentFocus();//获取当前activity中获得焦点的view
        }

        if (focusView != null) {//当前activity中有获得焦点的view，才进行掩藏软键盘
                /*
                if (focusView.isFocusable()) {
                    focusView.setFocusable(false);
                    focusView.setFocusable(true);
                }
                */
            if (focusView.isFocused()) {//取消获得焦点view的获取状态
                focusView.clearFocus();
            }
            //掩藏软键盘
            InputMethodManager manager = (InputMethodManager) focusView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(focusView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            manager.hideSoftInputFromInputMethod(focusView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 判断手机号是否合法
     */
    public static boolean isMobile(String mobile) {
        if (TextUtils.isEmpty(mobile)) {
            BlocksToast.get().showToast(R.string.phone_number_not_null);
            return false;
        }
        return true;
    }

    private static SoftReference<SingBlocksDialog> mServerUpdatingDialogReference;

    /**
     * 提示服务升级中对话框
     */
    public static void showServerUpdatingDialog(Activity activity, String errMsg) {
        if (mServerUpdatingDialogReference == null || mServerUpdatingDialogReference.get() == null) {
            SingBlocksDialog singBlocksDialog = new SingBlocksDialog(activity)
                    .setTitle(ResourceUtil.getString(R.string.system_upgrade_in_progress))
                    .setGotText(ResourceUtil.getString(R.string.close))
                    .setContent(errMsg)
                    .setContentGravityCenter(Gravity.LEFT);
            singBlocksDialog.setCanceledOnTouchOutside(false);
            mServerUpdatingDialogReference = new SoftReference<>(singBlocksDialog);
        }
        mServerUpdatingDialogReference.get().show();
    }

}
